

import Konva from 'konva'

export class IndexGroup extends Konva.Group {
  private indexMap: Map<string, Konva.Node> = new Map()
  private gridSize: number

  constructor(config: Konva.ContainerConfig) {
    super(config)
    this.gridSize = config.gridSize
  }

  addAt(x: number, y: number, child: Konva.Group | Konva.Shape): this {
    child.id(`${x}_${y}`)
    this.removeAt(x, y)
    child.setPosition({ x: x * this.gridSize, y: y * this.gridSize })
    this.indexMap.set(child.id(), child)
    this.add(child)
    return this
  }

  removeAt(x: number, y: number): this {
    const child = this.getAt(x, y)
    if (child) {
      child.destroy()
      this.indexMap.delete(child.id())
    }
    return this
  }

  getAt(x: number, y: number): Konva.Node | undefined {
    return this.indexMap.get(`${x}_${y}`)
  }

  clear(): this {
    const children = this.getChildren()
    children.forEach((child) => {
      child.remove()
      this.indexMap.delete(child.id())
    })
    this.indexMap.clear()
    return this
  }
}